import java.util.PriorityQueue;

/**
 * Created with IntelliJ IDEA.
 * Description:
 * User: 86183
 * Date: 2024-04-17
 * Time: 22:54
 */
class MyTimerTask implements Comparable<MyTimerTask>{
    private Runnable runnable;//任务
    private long time;//执行任务的时间
    public MyTimerTask(Runnable runnable,long delay){
        //传入的是延时执行时间,换算一下,变成绝对时间(时间戳)
        this.time = System.currentTimeMillis()+delay;
        this.runnable = runnable;
    }
    public long getTime(){
        return  time;
    }
    public void run(){
        runnable.run();//执行任务
    }

    @Override
    public int compareTo(MyTimerTask o) {
        return (int)(this.time-o.time);
    }
}
class MyTimer{
        Object locker=new Object();
    PriorityQueue<MyTimerTask> queue = new PriorityQueue<>();//使用优先级队列,管理多个任务
    public MyTimer(){

        Thread t=new Thread(()->{
            synchronized (locker){
                while(true){
                    if(queue.size()==0){
                        try {
                            locker.wait();
                        } catch (InterruptedException e) {
                            e.printStackTrace();
                        }
                    }
                    MyTimerTask task = queue.peek();
                    long curTime = System.currentTimeMillis();
                    if(curTime>= task.getTime()){
                        task.run();
                        queue.poll();//执行完之后将该任务从任务队列中删除
                    }else{
                        try {
                            locker.wait(task.getTime()-curTime);//阻塞时间
                        } catch (InterruptedException e) {
                            e.printStackTrace();
                        }
                    }

                }
            }

        });
        t.start();

    }
    public void schedule(Runnable runnable,long delay){
        MyTimerTask myTimerTask=new MyTimerTask(runnable,delay);
        synchronized (locker){
            queue.offer(myTimerTask);
            locker.notify();
        }

    }

}
public class Demo2 {
    public static void main(String[] args) {
        MyTimer myTimer=new MyTimer();
        myTimer.schedule(new Runnable() {
            @Override
            public void run() {
                System.out.println("hello 5000");
            }
        },5000);
        myTimer.schedule(new Runnable() {
            @Override
            public void run() {
                System.out.println("hello 1000");
            }
        },1000);

        myTimer.schedule(new Runnable() {
            @Override
            public void run() {
                System.out.println("hello 3000");
            }
        },3000);

    }
}
